<?php
/**
 * Created by PhpStorm.
 * User: mr2longly <mr2longly@gmail.com>
 * Date: 7/1/16
 * Time: 23:44
 */

namespace Common\Library\Http;


use Common\Library\BusinessException;
use Common\Library\Constant;
use Think\Log;
use Think\OpenapiDevBase;


class Request {
    public static $_DATA = array();

    public static $REQUEST_URI_UPLOAD = [
        '/Home/UserCenter/uploadImage' => '',
        '/Home/MerchantCRO/merchantUploadImage' => '',
    ];

    public static function parse() {
        $requestURI = !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
        if (isset(self::$REQUEST_URI_UPLOAD[$requestURI])) {
            // 跟客户端约定的上传图片接通用字段全在json字段中,并且只接受post方式
            $requestBodyString = $_POST['json'];
        } else {
            $requestBodyString = file_get_contents('php://input');
        }

        Log::write('RequestURI:' . $requestURI, Log::DEBUG);
        if(substr($_SERVER['REQUEST_URI'],0,14)<>'/Home/Crawler/') {
            Log::write($requestBodyString, Log::DEBUG);
        }

        if ($requestBodyString && ($data = json_decode($requestBodyString, true))) {
            if (IS_POST) {
                $_POST      = $data;
            } elseif (IS_GET) {
                $_GET       = $data;
            } else {
                $_REQUEST   = $data;
            }

            self::$_DATA    = $data;
        }
        //第三方爬虫推送接口不验签
        if(substr($_SERVER['REQUEST_URI'],0,14)=='/Home/Crawler/') {
            //不处理
        } elseif(substr($_SERVER['REQUEST_URI'],0,11)=='/Home/Rong/'){
            //融360-校验融360
            self::validate_rong();
        }else {
            // 验证数据签名
            self::validate();
        }
    }
    /********融360|请求接口|sign校验**********/
    public  function  validate_rong(){
        $strPost = file_get_contents('php://input');
        $postArray = json_decode($strPost,true);
        $data =  $postArray['biz_data'];
        $sign = $postArray['sign'];
        /*****************融360|公钥*******************/
        $rong = new OpenapiDevBase();
        $orgPublicKey = $rong->orgPublicKey;
        /*****************融360|公钥*******************/
        $ret = openssl_verify($data,base64_decode($sign),$orgPublicKey);
        if(!$ret){
            Log::rong_write("******融360|sign签名校验失败|Request/validate_rong*********");
            BusinessException::throwException(Constant::REQUEST_SIGN_UNMATCHED);
        }

    }
    /********融360|请求接口|sign校验**********/
    public static function validate() {
        $data = self::$_DATA;
        if (!$data || (isset($data['no_need_sign']) && $data['no_need_sign'])) {
            return;
        }

        if (!isset($data['sign']) || !($sign = $data['sign'])) {
            BusinessException::throwException(Constant::INVALID_PARAMETER);
        }

        $md5 = gen_sign($data);
        if (strtolower($data['sign']) !== $md5) {
            BusinessException::throwException(Constant::REQUEST_SIGN_UNMATCHED);
        }
    }
}
